package com.wlstock.funi.utils;


import android.content.Context;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.constant.SharePrefConstants;
import com.wlstock.funi.dao.AIAccountDao;
import com.wlstock.funi.dao.PositionDao;
import com.wlstock.funi.dao.SelfFundSetDao;
import com.wlstock.funi.dao.StrategyFundSelDao;
import com.wlstock.funi.dao.TradeHisDao;
import com.wlstock.funi.fundenum.TRADE_ERROR_STATE;
import com.wlstock.funi.model.AIAccountsModel;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.PositionModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.model.SelfFundSetModel;
import com.wlstock.funi.model.StrategyFundModel;
import com.wlstock.funi.request.QuickBuy;
import com.wlstock.funi.runnable.OrderBuy;
import com.wlstock.funi.runnable.OrderListener;

import java.util.Date;

public class BuyHelper implements OrderListener, QuickBuy.QuickBuyListener {
	private Context mContext;
	private static BuyHelper instance;
	private TradeManagerListener listener;

	private BuyHelper(Context mContext) {
		this.mContext = mContext;
	}

	public static BuyHelper getInstance(Context mContex) {
		if (instance == null) {
			synchronized (BuyHelper.class) {
				if (instance == null) {
					instance = new BuyHelper(mContex);
				}
			}
		}
		return instance;
	}


	/**
	 * 这里默认每次买入5000块
	 * @param curPrice
	 * @return
	 */
	public long getStkQTY(float curPrice){
		return CaculateUtils.caculateNums(SharePreferenceUtils.getFloatSP(mContext, SharePrefConstants.DEFAULT_MONEY,5000), curPrice);
	}

	public void buyAIStock(SelfFundModel tmpSelfFundModel) {
		SelfFundSetDao.getInstance(mContext).updatePendState(tmpSelfFundModel.getStockNo(), SelfFundSetModel.DONE, OperateModel.TradeType_BUY);
		NotiUtils.showSimpleNoti(mContext, NotiIdGenerator.ID_WILL_BUY, "模拟账户即将以" + tmpSelfFundModel.getCurPrice() + "买入" + tmpSelfFundModel.getStockName(), tmpSelfFundModel.getStockNo() + "  时间:" + TimeUtils.getCurrentHHMM(), R.drawable.ic_ai);

		AIAccountsModel aiModel = new AIAccountsModel();
		aiModel.setWithFundStock(tmpSelfFundModel);
		int stkQty = (int)getStkQTY(tmpSelfFundModel.getCurPrice());
		aiModel.setStkQty(stkQty);
		AIAccountDao.getInstance(mContext).addModel(aiModel);
		TradeHisDao.getInstance(mContext).addBUYModel(aiModel);

	}

	public void buyMyRealStock(SelfFundModel tmpSelfFundModel, SelfFundSetModel buySetModel,boolean isQuickBuy) {
		if (FundApplication.isLogSuccess && isQuickBuy) {
			OrderBuy buy = new OrderBuy(tmpSelfFundModel.getStockNo(), tmpSelfFundModel.getStockName(), tmpSelfFundModel.getCurPrice(), CaculateUtils.scaleNums(buySetModel.getTotalMoney() / tmpSelfFundModel.getCurPrice()));
			buy.buy(this);
			NotiUtils.showSimpleNoti(mContext, NotiIdGenerator.ID_WILL_BUY, "真实帐号即将以" + tmpSelfFundModel.getCurPrice() + "买入" + tmpSelfFundModel.nameWithCode(),"  时间:" + TimeUtils.getCurrentHHMM(), R.drawable.ic_buy);
		}
		if (!isQuickBuy){
			NotiUtils.showSimpleNoti(mContext, NotiIdGenerator.ID_WILL_BUY, "真实帐号检测" + tmpSelfFundModel.nameWithCode()+"出现买点","  时间:" + TimeUtils.getCurrentHHMM(), R.drawable.ic_buy);
			SelfFundSetDao.getInstance(mContext).updatePendState(tmpSelfFundModel.getStockNo(), SelfFundSetModel.DONE, OperateModel.TradeType_BUY);
		}
	}


	public void autoBuy(boolean isAutoBuy, TradeManagerListener tmListener) {
		this.listener = tmListener;
		String info = "";
		//判断时间是否在规定时间范围内
		info += "在规定时间:";
		if (TimeUtils.isHourInRange("09:30","09:35",new Date())){
			//市场情绪是否可买
			info += "✔️  市场情绪:";
			if (GlobalIndexHelper.getInstance(mContext).couldBuy()){
				//是否是最新仓位
				info += "✔️  最新仓位:";
				if (PositionDao.getInstance(mContext).isNewlyPosition(new Date())){
					PositionModel model = PositionDao.getInstance(mContext).getCurpositionModel();
					//仓位是否可买
					info += "✔️  有余仓可买:";
					if (isPostionBuyAble(model)){
						//可以买的金额
						int totalMoney = getBuyAbleMoney(model);
						info += "✔️  有余额可买:";
						if (totalMoney > 0){
							//买入的票子
							StrategyFundModel fundModel = StrategyFundSelDao.getInstance(mContext).queryBuyModelByOffsetDays(new Date(), 5);
							info += "✔️  有票子可买:";
							if (fundModel!=null){
								info += "✔️  自动买:";
								if (isAutoBuy){
									info += "✔";
									String stkNo = fundModel.getStkNo();
									String stkName = fundModel.getStkName();
									QuickBuy quickBuy = new QuickBuy(stkNo, stkName, totalMoney);
									quickBuy.qbListener = this;
									quickBuy.reqBuy(true);
									autoTradeListener(tmListener, TRADE_ERROR_STATE.STATE_SUCCESS,info);
								}else {
									info += "×";
									autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_NOT_AUTO,info);
								}
							}else {
								info += "×";
								autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_NOT_ANY_STOCK,info);
							}
						}else {
							info += "×";
							autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_NOT_ENOUGH_MONEY,info);
						}
					}else {
						info += "×";
						autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_BEYOND_BUYABLE_POSITION,info);
					}
				}else {
					info += "×";
					autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_NOT_NEW_POSITION,info);
				}
			}else {
				info += "×";
				autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_UNDER_GLOBAL_INDEX,info);
			}
		}else {
			info += "×";
			autoTradeListener(tmListener, TRADE_ERROR_STATE.ERROR_NOT_INTIME,info);
		}
	}

	public void autoTradeListener(TradeManagerListener tmListener, TRADE_ERROR_STATE state,String info){
		if (tmListener!=null){
			tmListener.autoBuyResult(state,info);
		}
	}

	/**
	 * 先检查异常
	 * @return 返回当前仓位是否小于或等于仓位上限
	 */
	public boolean isPostionBuyAble(PositionModel model) {
		if (model.getTotalAsserts()<0 ||model.getUseableFund()<=0  || model.getCurPostion()<0)
			return false;
		float exptectPosition = GlobalIndexHelper.getInstance(mContext).getExptectPosition();
		return model.getCurPostion() <= exptectPosition;
	}

	/**
	 * 先检查异常
	 * 最后返回允许买的金额
	 * @return
	 */
	public int getBuyAbleMoney(PositionModel model) {
		if (model.getTotalAsserts()<0 ||model.getUseableFund()<=0  || model.getCurPostion()<0){
			return 0;
		}
		float expectPostion = GlobalIndexHelper.getInstance(mContext).getExptectPosition();
		float curPostion = model.getCurPostion();
		if (expectPostion < curPostion)
			return 0;
		int money = (int)((expectPostion - curPostion)*model.getTotalAsserts());
		return money;
	}

	@Override
	public void orderSuccess(int tradeType, String stkcode, String stkName, float price, long qty) {
		if (tradeType == OperateModel.TradeType_BUY){

		}
	}

	@Override
	public void orderFaile(int tradeType, String stkcode, String stkName, float price, long qty, String info) {
		if (tradeType == OperateModel.TradeType_BUY){

		}
	}

	@Override
	public void getBuyInfo(boolean isSuccess, String stkCode, String stkName, float price, QuickBuy.BUYMODE mode, String pty, int totalMoney) {

	}
}
